package code.command {

import code.Model;
import code.event.RegisterEvent;
import code.remote.ResultReceivedEvent;
import code.remote.request.FetchUsersRequest;
import code.remote.request.UserRegisterRequest;

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import logging.Logger;

import mx.controls.Alert;
import mx.core.Application;

public class RegisterCommand implements ICommand {
	
	private static const LOG: Logger = Logger.getLogger("code.command.RegisterCommand");
	
	public function RegisterCommand() {
	}

	public function execute(_event: CairngormEvent): void {
		const event: RegisterEvent = _event as RegisterEvent;
		LOG.fine("Executing register [event="+event+"].");
		
		const m: Model = Model.instance;
		const req: UserRegisterRequest = new UserRegisterRequest(m.loginUsername, m.loginPassword, m.loginEmail);
		req.addEventListener(ResultReceivedEvent.RESULT_RECEIVED, onResultReceived);
		Model.instance.isLoginBlocked = true;
		req.doSend();
	}
	
	private function onResultReceived(event: ResultReceivedEvent): void {
		const userId: int = int(event.resultEvent.result.Result.UserId);
		
		if(userId == -1) {
			Alert.show("The desired username is already in use!", "Registration Failed");
		} else {
			Alert.show("You successfully registered as '" + Model.instance.loginUsername + "'.", "Registration Succeeded");
			
			new FetchUsersRequest().doSend();
			
			Application.application.loginPanel.currentState = '';
			Model.instance.loginEmail = '';
			// Application.application.currentState='stateMain';
		}
		
		Model.instance.isLoginBlocked = false;
	}
}
}